<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Model\User;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Utils\Context;


class AuthUser implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {

        $token = $this->request->header('Authorization');
        $token = str_replace('Bearer ', '', $token);

        $user = User::query()->where(['token' => $token])->first();
        if (!$user) {
            return $this->response->json(
                [
                    'status' => STATUS_FAILURE,
                    'message' => '用户认证失败'
                ]
            );
        }
        $request = $request->withAttribute('authUser', $user);
        Context::set(ServerRequestInterface::class, $request);

        return $handler->handle($request);
    }
}
